package com.xt.xxb.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xt.xxb.Main;
import com.xt.xxb.SimpleHttpClient;
import com.xt.xxb.taobao.TbApi;
import com.xt.xxb.taobao.TbResponse;
import com.xt.xxb.taobao.ThreadPoolUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

/**
 * 订单接口
 */
public class OrderRunnable implements Runnable {
    private final static String API_URL = "%s/api/xy/store/order";
    private final static String API_URL_NOTIFY = "%s/api/xy/store/notify";

    public OrderRunnable() {

    }

    @Override
    public void run() {
        boolean login = Main.isLogin();
        if (!login) {
            return;
        }
        String cookies = Main.getCookiesStr();
        String gateway = Main.getSysInfo().getGateway();
        String sysUser = Main.getSysInfo().getSysUser();
        String sysPass = Main.getSysInfo().getSysPass();
        String user = Main.getSysInfo().getUser();
        String pass = Main.getSysInfo().getPass();
        String key = Main.RANDOM_KEY;
        try {
            String reqUrl = String.format(API_URL, gateway);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("sysUser", sysUser);
            jsonObject.put("sysPass", sysPass);
            jsonObject.put("user", user);
            jsonObject.put("pass", pass);
            jsonObject.put("key", key);
            HttpResponse response = SimpleHttpClient.post(reqUrl, jsonObject);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            if (result == null || result.isEmpty()) {
                Main.logger("暂无待支付订单");
                return;
            }
            JSONObject respJson = JSONObject.parseObject(result);
            if (!respJson.getBoolean("success")) {
                Main.logger(respJson.getString("message"));
                return;
            }
            if (!respJson.containsKey("data")) {
                Main.logger("暂无待支付订单");
                return;
            }
            JSONArray objects = respJson.getJSONArray("data");
            if (objects == null || objects.isEmpty()) {
                Main.logger("暂无待支付订单");
                return;
            }
            for (Object item : objects) {
                String orderId = String.valueOf(item);
                ThreadPoolUtils.execute(() -> {
                    try {
                        TbResponse tbResponse = TbApi.orderQuery(cookies, orderId);
                        if (tbResponse.isSuccess()) {
                            JSONObject respOrder = (JSONObject) tbResponse.getData();
                            JSONObject statusInfo = respOrder.getJSONObject("statusInfo");
                            JSONObject payInfo = respOrder.getJSONObject("payInfo");
                            String text = statusInfo.getString("text");
                            if (text.equals("等待买家付款")) {
                                return;
                            }
                            if (text.equals("交易成功") || text.equals("卖家已发货") || text.equals("买家已付款")) {
                                String actualFee = payInfo.getString("actualFee");
                                notify(orderId, actualFee, "1");
                            } else if (text.equals("交易关闭")) {
                                notify(orderId, "0", "2");
                            }
                        } else {
                            Main.logger("订单[" + orderId + "]查询失败，原因：" + tbResponse.getErrorMsg());
                        }
                    } catch (Exception e) {
                        Main.logger("订单[" + orderId + "]查询失败，原因：" + e.getMessage());
                    }
                });
            }
        } catch (Exception e) {
            Main.logger("订单数据获取失败，原因：" + e.getMessage());
        }
    }

    /**
     * 订单通知
     *
     * @param orderId
     * @param amount
     * @param status
     */
    private void notify(String orderId, String amount, String status) {
        String gateway = Main.getSysInfo().getGateway();
        String sysUser = Main.getSysInfo().getSysUser();
        String sysPass = Main.getSysInfo().getSysPass();
        String user = Main.getSysInfo().getUser();
        String pass = Main.getSysInfo().getPass();
        String key = Main.RANDOM_KEY;
        try {
            String reqUrl = String.format(API_URL_NOTIFY, gateway);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("sysUser", sysUser);
            jsonObject.put("sysPass", sysPass);
            jsonObject.put("user", user);
            jsonObject.put("pass", pass);
            jsonObject.put("key", key);
            jsonObject.put("orderNo", orderId);
            jsonObject.put("amount", amount);
            jsonObject.put("status", status);
            HttpResponse response = SimpleHttpClient.post(reqUrl, jsonObject);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            if (result == null || result.isEmpty()) {
                Main.logger("订单[" + orderId + "]通知下发失败，服务器无响应");
                return;
            }
            JSONObject respJson = JSONObject.parseObject(result);
            if (respJson.getBoolean("success")) {
                Main.logger("订单[" + orderId + "]通知下发成功");
                return;
            }
            String message = respJson.getString("message");
            Main.logger("订单[" + orderId + "]通知下发失败，原因：" + message);
        } catch (Exception e) {
            Main.logger("订单[" + orderId + "]通知下发失败，服务器请求异常[" + e.getMessage() + "]");
        }
    }
}
